from flask import Flask, jsonify, request
from flask_cors import CORS
import pymysql.cursors
from collections import Counter
import re

app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": "*"}})


# Define a function to create a new connection
def create_connection():
    return pymysql.connect(host='localhost',
                           user='root',
                           password='123456',
                           database='db01;',
                           cursorclass=pymysql.cursors.DictCursor)


@app.route('/getjiqixueData')
def getjiqixueData():
    try:
        connection = create_connection()
        with connection.cursor() as cursor:
            sql = "SELECT * FROM 123"
            cursor.execute(sql)
            result = cursor.fetchall()
        return jsonify(result)
    except Exception as e:
        return jsonify({"error": str(e)}), 500
    finally:
        connection.close()


@app.route('/AIData')
def AIData():
    try:
        connection = create_connection()
        with connection.cursor() as cursor:
            sql = "SELECT * FROM 123 where type=2"
            cursor.execute(sql)
            result = cursor.fetchall()
        return jsonify(result)
    except Exception as e:
        return jsonify({"error": str(e)}), 500
    finally:
        connection.close()


@app.route('/ruanjiankaifaData')
def ruanjiankaifaData():
    try:
        connection = create_connection()
        with connection.cursor() as cursor:
            sql = "SELECT * FROM 123 where type=3"
            cursor.execute(sql)
            result = cursor.fetchall()
        return jsonify(result)
    except Exception as e:
        return jsonify({"error": str(e)}), 500
    finally:
        connection.close()


@app.route('/getjiqixueSkillEcharts')
def getjiqixueSkillEcharts():
    try:
        connection = create_connection()
        with connection.cursor() as cursor:
            sql = "SELECT skills FROM 123 where type=1"
            cursor.execute(sql)
            result = cursor.fetchall()

        infos = []
        for item in result:
            infos.extend(item['skills'].replace(" ", "").split("\n"))

        counter = Counter(infos)
        most_common_skills = counter.most_common(10)

        X = [skill for skill, count in most_common_skills]
        Y = [count for skill, count in most_common_skills]

        return jsonify({'X': X, 'Y': Y})
    except Exception as e:
        return jsonify({"error": str(e)}), 500
    finally:
        connection.close()


@app.route('/AISkillEcharts')
def AISkillEcharts():
    try:
        connection = create_connection()
        with connection.cursor() as cursor:
            sql = "SELECT skills FROM 123 where type=2"
            cursor.execute(sql)
            result = cursor.fetchall()

        infos = []
        for item in result:
            infos.extend(item['skills'].replace(" ", "").split("\n"))

        counter = Counter(infos)
        most_common_skills = counter.most_common(10)

        X = [skill for skill, count in most_common_skills]
        Y = [count for skill, count in most_common_skills]

        return jsonify({'X': X, 'Y': Y})
    except Exception as e:
        return jsonify({"error": str(e)}), 500
    finally:
        connection.close()


@app.route('/ruanjianSkillEcharts')
def ruanjianSkillEcharts():
    try:
        connection = create_connection()
        with connection.cursor() as cursor:
            sql = "SELECT skills FROM 123 where type=3"
            cursor.execute(sql)
            result = cursor.fetchall()

        infos = []
        for item in result:
            infos.extend(item['skills'].replace(" ", "").split("\n"))

        counter = Counter(infos)
        most_common_skills = counter.most_common(10)

        X = [skill for skill, count in most_common_skills]
        Y = [count for skill, count in most_common_skills]

        return jsonify({'X': X, 'Y': Y})
    except Exception as e:
        return jsonify({"error": str(e)}), 500
    finally:
        connection.close()


@app.route('/getruanjianSkillEcharts')
def getruanjianSkillEcharts():
    try:
        connection = create_connection()
        with connection.cursor() as cursor:
            sql = "SELECT skills FROM 123 where type=3"
            cursor.execute(sql)
            result = cursor.fetchall()

        infos = []
        for item in result:
            infos.extend(item['skills'].replace(" ", "").split("\n"))

        counter = Counter(infos)
        most_common_skills = counter.most_common(10)

        X = [skill for skill, count in most_common_skills]
        Y = [count for skill, count in most_common_skills]

        return jsonify({'X': X, 'Y': Y})
    except Exception as e:
        return jsonify({"error": str(e)}), 500
    finally:
        connection.close()


@app.route('/getjiqixueEducationEcharts')
def getjiqixueEducationEcharts():
    try:
        connection = create_connection()
        with connection.cursor() as cursor:
            sql = "SELECT education FROM 123 where type=1"
            cursor.execute(sql)
            result = cursor.fetchall()
            # infos = []
            # for item in result:
            #     if item["education"].replace(" ", "").replace("\n", ""):
            #         infos.extend(item["education"].replace(" ", "").replace("\n", ""))
            # infos = (Counter(infos).most_common())
            #
            # arr = []
            # for item in infos:
            #     obj = {}
            #     obj["value"] = item[1]
            #     obj["name"] = item[0]
            #     arr.append(obj)
            # print(arr)
            # return jsonify(arr)
        educations = [item['education'].strip() for item in result if item['education']]
        education_counter = Counter(educations)
        top_educations = education_counter.most_common()

        education_data = [{"name": education, "value": count} for education, count in top_educations]

        return jsonify(education_data)
    except Exception as e:
        return jsonify({"error": str(e)}), 500
    finally:
        connection.close()


@app.route('/getAIEducationEcharts')
def getAIEducationEcharts():
    try:
        connection = create_connection()
        with connection.cursor() as cursor:
            sql = "SELECT education FROM 123 where type=2"
            cursor.execute(sql)
            result = cursor.fetchall()
            # infos = []
            # for item in result:
            #     if item["education"].replace(" ", "").replace("\n", ""):
            #         infos.extend(item["education"].replace(" ", "").replace("\n", ""))
            # infos = (Counter(infos).most_common())
            #
            # arr = []
            # for item in infos:
            #     obj = {}
            #     obj["value"] = item[1]
            #     obj["name"] = item[0]
            #     arr.append(obj)
            # print(arr)
            # return jsonify(arr)
        educations = [item['education'].strip() for item in result if item['education']]
        education_counter = Counter(educations)
        top_educations = education_counter.most_common()

        education_data = [{"name": education, "value": count} for education, count in top_educations]

        return jsonify(education_data)
    except Exception as e:
        return jsonify({"error": str(e)}), 500
    finally:
        connection.close()


@app.route('/getruanjianEducationEcharts')
def getruanjianEducationEcharts():
    try:
        connection = create_connection()
        with connection.cursor() as cursor:
            sql = "SELECT education FROM 123 where type=3"
            cursor.execute(sql)
            result = cursor.fetchall()
            # infos = []
            # for item in result:
            #     if item["education"].replace(" ", "").replace("\n", ""):
            #         infos.extend(item["education"].replace(" ", "").replace("\n", ""))
            # infos = (Counter(infos).most_common())
            #
            # arr = []
            # for item in infos:
            #     obj = {}
            #     obj["value"] = item[1]
            #     obj["name"] = item[0]
            #     arr.append(obj)
            # print(arr)
            # return jsonify(arr)
        educations = [item['education'].strip() for item in result if item['education']]
        education_counter = Counter(educations)
        top_educations = education_counter.most_common()

        education_data = [{"name": education, "value": count} for education, count in top_educations]

        return jsonify(education_data)
    except Exception as e:
        return jsonify({"error": str(e)}), 500
    finally:
        connection.close()


# @app.route('/getjiqixueEduAnd123Echarts')
# def getjiqixueEduAnd123Echarts():
#     try:
#         connection = create_connection()
#         with connection.cursor() as cursor:
#             sql = "SELECT education,123 FROM 123"
#             cursor.execute(sql)
#             result = cursor.fetchall()
#             total = {}
#             totalnum = {}
#         for item in result:
#             if item["education"]:
#                 edu = item["education"].replace(" ", "").replace("\n", "")
#             price = item["123"].replace(" ", "").replace("\n", "")
#         print(price)
#         if not (re.findall("天", price)) and re.findall("千|万", price):
#             nums = re.findall("\d+\.{0,1}\d*", price)
#             flags = re.findall("千|万", price)
#             num1 = float(nums[0]) * 1000 if flags[0] == "千" else float(nums[0]) * 10000
#             num2 = float(nums[1]) * 1000 if flags[1] == "千" else float(nums[1]) * 10000
#             avg = (num1 + num2) / 2
#             if total.get(edu):
#                 total[edu] += avg
#                 totalnum[edu] += 1
#             else:
#                 total[edu] = avg
#                 totalnum[edu] = 1
#                 X = []
#                 Y = []
#                 for item in total:
#                     X.append(item)
#                     Y.append(total[item] / totalnum[item])
#                     print(X)
#                     print(Y)
#                     return [X, Y]
#     except Exception as e:
#         return jsonify({"error": str(e)}), 500
#     finally:
#         connection.close()
@app.route('/getjiqixueEduAnd123Echarts')
def getjiqixueEduAnd123Echarts():
    try:
        connection = create_connection()
        with connection.cursor() as cursor:
            sql = "SELECT education, 123 FROM 123 where type=1"
            cursor.execute(sql)
            result = cursor.fetchall()
            total = {}
            totalnum = {}

        for item in result:
            if item["education"]:
                edu = item["education"].strip()
                price = item["123"].strip()
                if not re.findall("天", price) and re.findall("千|万", price):
                    nums = re.findall(r"\d+\.{0,1}\d*", price)
                    flags = re.findall("千|万", price)
                    num1 = float(nums[0]) * 1000 if flags[0] == "千" else float(nums[0]) * 10000
                    num2 = float(nums[1]) * 1000 if flags[1] == "千" else float(nums[1]) * 10000
                    avg = (num1 + num2) / 2
                    if edu in total:
                        total[edu] += avg
                        totalnum[edu] += 1
                    else:
                        total[edu] = avg
                        totalnum[edu] = 1

        X = list(total.keys())
        Y = [total[edu] / totalnum[edu] for edu in X]

        return jsonify({"X": X, "Y": Y})
    except Exception as e:
        return jsonify({"error": str(e)}), 500
    finally:
        connection.close()


@app.route('/getAIEduAnd123Echarts')
def getAIEduAnd123Echarts():
    try:
        connection = create_connection()
        with connection.cursor() as cursor:
            sql = "SELECT education, 123 FROM 123 where type=2"
            cursor.execute(sql)
            result = cursor.fetchall()
            total = {}
            totalnum = {}

        for item in result:
            if item["education"]:
                edu = item["education"].strip()
                price = item["123"].strip()
                if not re.findall("天", price) and re.findall("千|万", price):
                    nums = re.findall(r"\d+\.{0,1}\d*", price)
                    flags = re.findall("千|万", price)
                    num1 = float(nums[0]) * 1000 if flags[0] == "千" else float(nums[0]) * 10000
                    num2 = float(nums[1]) * 1000 if flags[1] == "千" else float(nums[1]) * 10000
                    avg = (num1 + num2) / 2
                    if edu in total:
                        total[edu] += avg
                        totalnum[edu] += 1
                    else:
                        total[edu] = avg
                        totalnum[edu] = 1

        X = list(total.keys())
        Y = [total[edu] / totalnum[edu] for edu in X]

        return jsonify({"X": X, "Y": Y})
    except Exception as e:
        return jsonify({"error": str(e)}), 500
    finally:
        connection.close()


@app.route('/getruanjianEduAnd123Echarts')
def getruanjianEduAnd123Echarts():
    try:
        connection = create_connection()
        with connection.cursor() as cursor:
            sql = "SELECT education, 123 FROM 123 where type=3"
            cursor.execute(sql)
            result = cursor.fetchall()
            total = {}
            totalnum = {}

        for item in result:
            if item["education"]:
                edu = item["education"].strip()
                price = item["123"].strip()
                if not re.findall("天", price) and re.findall("千|万", price):
                    nums = re.findall(r"\d+\.{0,1}\d*", price)
                    flags = re.findall("千|万", price)
                    num1 = float(nums[0]) * 1000 if flags[0] == "千" else float(nums[0]) * 10000
                    num2 = float(nums[1]) * 1000 if flags[1] == "千" else float(nums[1]) * 10000
                    avg = (num1 + num2) / 2
                    if edu in total:
                        total[edu] += avg
                        totalnum[edu] += 1
                    else:
                        total[edu] = avg
                        totalnum[edu] = 1

        X = list(total.keys())
        Y = [total[edu] / totalnum[edu] for edu in X]

        return jsonify({"X": X, "Y": Y})
    except Exception as e:
        return jsonify({"error": str(e)}), 500
    finally:
        connection.close()


@app.route("/getSkillScore")
def getSkillScore():
    try:
        connection = create_connection()
        with connection.cursor() as cursor:
            sql = "select skills from 123 where type=1"
            cursor.execute(sql)
            result = cursor.fetchall()
            connection.commit()
            infos = []
            for item in result:
                infos += (item["skills"].replace(" ", "").split("\n"))
                infos = (Counter(infos))
                infos = infos.most_common()
                total = 0
                newinfos = []
                for item in infos:
                    if item[0]:
                        total += item[1]
                        newinfos.append(list(item))
                        for item in newinfos:
                            item[1] = item[1] / total
                            return newinfos
    except Exception as e:
        return jsonify({"error": str(e)}), 500
    finally:
        connection.close()


@app.route("/predict")
def predict():
    try:
        connection = create_connection()
        with connection.cursor() as cursor:
            X = []
            city = float(request.args.get("city"))
            workage = float(request.args.get("workage"))
            education = float(request.args.get("education"))
            skills = request.args.get("skills")
            nums = 0
            for item in skills.split(","):
                nums += float(item)
                X.append(1)
                X.append(city)
                X.append(education)
                X.append(workage)
                X.append(nums)
                from theta import theta
                import numpy as np
                X = np.array(X)
                theta = np.array(theta)
                return str(X.dot(theta))
    except Exception as e:
        return jsonify({"error": str(e)}), 500
    finally:
        connection.close()


if __name__ == '__main__':
    app.run(debug=True)
